package com.yeti.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.yeti.form.RegistroForm;
import com.yeti.service.ClienteService;

@Controller
public class InicioController {
		
		@Autowired
		ClienteService clienteService;
		
		@Autowired
		private MessageSource messageSource;

		@RequestMapping(value="/registro", method = RequestMethod.GET)
		public String Registro(ModelMap model) {
				model.addAttribute("registroForm", new RegistroForm());
			return "/inicio/registro";
		}
		
		@RequestMapping(value="/registrar", method = RequestMethod.POST)
		public String Registrar(@Valid RegistroForm registroForm, BindingResult result, ModelMap model) {
			if(clienteService.exists(registroForm.getUser())){
				result.addError(new ObjectError("user",messageSource.getMessage("Exist.registroForm.user", null, Locale.getDefault())));
			}
			if(result.hasErrors()) {
	            return "/inicio/registro";
	        }
			if(!clienteService.registrar(registroForm)){
				result.addError(new ObjectError("others",messageSource.getMessage("OtherError.registroForm.all", null, Locale.getDefault())));
				return "/inicio/registro";
			}
			return "/inicio/registrado";
		}
		
		@RequestMapping(value="/registrar", method = RequestMethod.GET)
		public String RegistrarGet(ModelMap model) {
			model.addAttribute("registroForm", new RegistroForm());    
			return "/inicio/registro";
		}
		
//		Convierte fechas de String a date
		
		@InitBinder
		public void initBinder(WebDataBinder webDataBinder) {
		 SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		 dateFormat.setLenient(false);
		 webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
		 }

		
	}
